package com.lagou.handler;

import com.lagou.bean.ApplicationContextFactory;
import com.lagou.pojo.RpcResponse;
import com.lagou.pojo.RpcRequest;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
@ChannelHandler.Sharable
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        ctx.pipeline();
    }

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 1.判断当前的请求是否符合规则
        if (msg instanceof RpcRequest) {
            System.out.println("当前服务器被调用");
            RpcRequest request = (RpcRequest) msg;

            // 2.获取请求接口、实现类，通过反射调用方法
            String className = request.getClassName();
            Class<?> clazz = Class.forName(className);

            // 从初始化容器中获取实现类对象
            Object bean = ApplicationContextFactory.applicationContext.getBean(clazz);
            String methodName = request.getMethodName();

            // 通过方法名和形参列表匹配到方法
            Method method = bean.getClass().getDeclaredMethod(methodName, request.getParameterTypes());
            // 3.通过反射调动方法
            Object result = method.invoke(bean, request.getParameters());

            // 4.通过RpcResponse返回值
            RpcResponse response = new RpcResponse();
            response.setRequestId(request.getRequestId());
            response.setObject(result);

            // 5.结果输出到客户端
            ctx.writeAndFlush(response);
        }
    }

}
